package cn.yuanqiao.archive.storeRoom.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.TenantYqdaFolder;
import cn.yuanqiao.archive.storeRoom.domain.*;
import cn.yuanqiao.archive.storeRoom.mapper.*;
import cn.yuanqiao.archive.storeRoom.service.IUpDownShelvesService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UpDownShelvesServiceImpl implements IUpDownShelvesService {

    private static final Logger log = LoggerFactory.getLogger(UpDownShelvesServiceImpl.class);


    @Autowired
    private UpDownShelvesMapper upDownShelvesMapper;

    @Autowired
    private GridMapper gridMapper;
    @Autowired
    private BoxMapper boxMapper;

    @Autowired
    private UpDownLogsMapper upDownLogsMapper;

    @Autowired
    private StoreroomMapper storeroomMapper;
    @Autowired
    private DaBoxMapper daBoxMapper;
    @Autowired
    private ShelfMapper shelfMapper;
    @Autowired
    private InitializationMapper initializationMapper;

    @Override
    public List<UpDownShelves> getList(Box box) {
        String code=SecurityUtils.getTenantCode().toUpperCase();
        if(StringUtils.isEmpty(code)){
            //抛出异常
            throw new ServiceException("TenantCode is null");
        }
        try{
            String SjType=box.getSjType();
            String type=box.getType();
            List<UpDownShelves> list=new ArrayList();
            //按盒
            if("0".equals(SjType)){
                if("0".equals(type)){
                    //上架
                    list=boxMapper.getSjBoxList(code,box.getKeyword());
                }else if("1".equals(type)){
                    //下架
                    list=boxMapper.getBoxList(code,box.getGridId(),box.getKeyword());
                }
            }else if("1".equals(SjType)){
                //按卷
                if("0".equals(type)){
                    //上架
                    list=boxMapper.getSjBoxListByfolderId(code,box.getKeyword());
                }else if("1".equals(type)){
                    //下架
                    list=boxMapper.getBoxListByfolderId(code,box.getGridId(),box.getKeyword());
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean offShelf(Map map) {
        String code=SecurityUtils.getTenantCode().toUpperCase();
        if(StringUtils.isEmpty(code)){
            //可能需要抛出异常
            throw new ServiceException("TenantCode is null");
        }
        String type=map.get("type").toString();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //预留计算档案格剩余空间
        Long gz_id= Long.parseLong((String) map.get("gzId"));//格子id  可用来计算
        Long kf_id=Long.parseLong(map.get("kfId").toString());
        Storeroom storeroom=storeroomMapper.selectStoreroomByStoreId(kf_id,code);

        //前端如果勾选了全选按钮   需要给 ids 去重
        String ids=String.valueOf(map.get("ids"));//选择上架的盒子或者案卷
        String[] strArray = ids.split(",");
        Set<String> staffsSet = new HashSet<String>(Arrays.asList(strArray));
        String[] result = staffsSet.toArray(new String[staffsSet.size()]);

        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sbf.format(d);
        //根据ids和门类code查询是哪条数据   把规格查询出来
        boolean boString=false;
        int num=0;
        //下架之前先验证该盒子是否已出库
        try {
            String sql="";
            for (int i = 0; i < staffsSet.size(); i++) {//遍历出来是  id+menleicode
                String id = result[i];
                String[] result1 = id.split(";");
                Long id1 = Long.parseLong(result1[0]);
                String subtablename = result1[1];
                //根据subtablename   判断后缀  STORE_MODE整理方式
                String sqlString = "";
                ArrayList<Map<String, Object>> singleListBySql = new ArrayList<>();

                String[] subArr = subtablename.split("_");
                if ("F".equals(subArr[subArr.length - 2])) {
                    singleListBySql = upDownShelvesMapper.getCategoryByDa(subtablename, code, "");
                } else if ("V".equals(subArr[subArr.length - 2])) {
                    singleListBySql = upDownShelvesMapper.getCategoryByDa("", code, subtablename);
                }
                String STORE_MODE = singleListBySql.get(0).get("STORE_MODE").toString();
                if (type.equals("1")) {//按卷上架，修改卷表
                    /*  int zongys=upDownShelvesMapper.getSumYs(id1,code);*/
                    num = upDownShelvesMapper.updateState(id1, code, SecurityUtils.getUserId(), new Date(), 0L);
                    //根据格子id修改格子表的上架盒数和剩余空间  是否修改格子数此处存疑
                    /*     num= upDownShelvesMapper.offShelffolderId(zongys,gz_id,code);*/
                    upDownShelvesMapper.updateGridByBox(gz_id, code);
                    Map<String, Object> map1 = upDownShelvesMapper.getDaMessageById(subtablename, id1);
                    if (map1 == null) {
                        map1 = new HashMap<>();

                    }
                    //自动添加出入库登记记录   根据foLder_id  查询件da_id 循环添加数据
                    UpDownLogs upDownLogs = new UpDownLogs();
                    upDownLogs.setCreator(SecurityUtils.getUserId());
                    upDownLogs.setDaId(id1);
                    upDownLogs.setCreateTime(new Date());
                    upDownLogs.setSubTableName(subtablename);
                    upDownLogs.setSxjgzry(SecurityUtils.getLoginUser().getUser().getNickName());
                    upDownLogs.setSxjrq(new Date());
                    upDownLogs.setType("下架");
                    upDownLogs.setXjyy(map.get("xjyy").toString());
                    upDownLogs.setRemark(map.get("bz") == null ? "" : map.get("bz").toString());
                    upDownLogs.setTitle(map1.get("TITLE") == null ? "" : map1.get("TITLE").toString());
                    upDownLogs.setDh(map1.get("DH") == null ? "" : map1.get("DH").toString());
                    upDownLogs.setStoreCode(storeroom.getStoreCode());
                    upDownLogs.setStoreName(storeroom.getStoreName());
                    upDownLogsMapper.insertUpDownLogs(upDownLogs);
                    //卷 SJ_POSITION
                    sql+=" UPDATE "+subtablename+" SET SJ_POSITION='' WHERE ID="+id1+"; UPDATE "+code+"_YQFOLDER SET SJ_POSITION='' WHERE FOLDER_ID="+id1+"; ";
                    //通过卷获取到所有件去修改 将他的倒数第2位替换或者去Category表里查询表
                    String jianTableName=upDownShelvesMapper.selectTableName(subtablename,new TenantCategory().getTableName());
                    String jianIds=upDownShelvesMapper.selectJianIds(id1,new TenantYqdaFolder().getTableName());
                    if(!StringUtils.isEmpty(jianIds)){
                        sql+=" UPDATE "+jianTableName+" SET SJ_POSITION='' WHERE ID in ("+jianIds+"); UPDATE "+code+"_YQDA SET SJ_POSITION='' WHERE DA_ID IN ("+jianIds+") ; ";
                    }





                } else if (type.equals("0") || STORE_MODE == null) {//按盒上架，修改盒表
                    num = upDownShelvesMapper.updateState(0L, code, SecurityUtils.getUserId(), new Date(), id1);
                    //根据type  判断是卷还是件 如果是件
                    //根据格子id修改格子表的上架盒数和剩余空间
                    int zongys = 0;
           /*     Map<String,Object>  specMap =upDownShelvesMapper.getSpecByBoxId(id1,code);
                String dw=specMap.get("SPEC_DW").toString();
                if(dw.equals("0")){
                    zongys+=Integer.parseInt(specMap.get("SPEC_NAME").toString());
                }else if(dw.equals("1")){
                    zongys+=Integer.parseInt(specMap.get("SPEC_NAME").toString())*10;
                }

               */
                    upDownShelvesMapper.updateGridByBox(gz_id, code);
                    //插入日志
                    ArrayList<Map<String, Object>> hedaidlist = daBoxMapper.getDaIdListByBoxId(id1, code);
                    for (Map map1 : hedaidlist) {
                        String tableName=map1.get("SUB_TABLE_NAME").toString();

                        Map<String, Object> map2 = upDownShelvesMapper.getDaMessageById(tableName, Long.parseLong(map1.get("DA_ID").toString()));
                        if (map2 == null) {
                            map2 = new HashMap<>();

                        }
                        UpDownLogs upDownLogs = new UpDownLogs();
                        upDownLogs.setCreator(SecurityUtils.getUserId());
                        upDownLogs.setDaId(Long.parseLong(map1.get("DA_ID").toString()));
                        upDownLogs.setCreateTime(new Date());
                        upDownLogs.setSubTableName(tableName);
                        upDownLogs.setSxjgzry(SecurityUtils.getLoginUser().getUser().getNickName());
                        upDownLogs.setSxjrq(new Date());
                        upDownLogs.setType("下架");
                        upDownLogs.setXjyy(map.get("xjyy").toString());
                        upDownLogs.setRemark(map.get("bz") == null ? "" : map.get("bz").toString());
                        upDownLogs.setTitle(map2.get("TITLE") == null ? "" : map2.get("TITLE").toString());
                        upDownLogs.setDh(map2.get("DH") == null ? "" : map2.get("DH").toString());
                        upDownLogs.setStoreCode(storeroom.getStoreCode());
                        upDownLogs.setStoreName(storeroom.getStoreName());
                        upDownLogsMapper.insertUpDownLogs(upDownLogs);
                        //通过da_id 将表进行
                        String[] tableNameArr = tableName.split("_");

                        if ("F".equals(tableNameArr[tableNameArr.length - 2])) {
                            //件 SJ_POSITION
                            sql+=" UPDATE "+tableName+" SET SJ_POSITION='' WHERE ID="+Long.parseLong(map1.get("DA_ID").toString())+"; UPDATE "+code+"_YQDA SET SJ_POSITION='' WHERE DA_ID="+Long.parseLong(map1.get("DA_ID").toString())+"; ";


                        } else if ("V".equals(tableNameArr[tableNameArr.length - 2])) {
                            //卷 SJ_POSITION
                            sql+=" UPDATE "+tableName+" SET SJ_POSITION='' WHERE ID="+Long.parseLong(map1.get("DA_ID").toString())+"; UPDATE "+code+"_YQFOLDER SET SJ_POSITION='' WHERE FOLDER_ID="+Long.parseLong(map1.get("DA_ID").toString())+"; ";
                            //通过卷获取到所有件去修改 将他的倒数第2位替换或者去Category表里查询表
                            String jianTableName=upDownShelvesMapper.selectTableName(tableName,new TenantCategory().getTableName());
                            String jianIds=upDownShelvesMapper.selectJianIds(Long.parseLong(map1.get("DA_ID").toString()),new TenantYqdaFolder().getTableName());
                            if(!StringUtils.isEmpty(jianIds)){
                                sql+=" UPDATE "+jianTableName+" SET SJ_POSITION='' WHERE ID in ("+jianIds+"); UPDATE "+code+"_YQDA SET SJ_POSITION='' WHERE DA_ID IN ("+jianIds+") ; ";




                            }


                        }
                    }


                }
            }
            //执行sql
            if(!StringUtils.isEmpty(sql)){
                //如果不为空那么就执行sql
                initializationMapper.createTable(sql);



            }
        }catch (Exception ex){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            log.error("下架失败",ex.getMessage());
            throw new ServiceException("下架失败!");

            //  ex.printStackTrace();
        }
        if(num>0){
        boString=true;
        }
        return boString;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String grounding(Map map) {
        String code=SecurityUtils.getTenantCode().toUpperCase();
        //预留计算档案格剩余空间
        Long gz_id= Long.parseLong(String.valueOf(map.get("gzId")));//格子id  可用来计算
        Long kf_id=Long.parseLong(map.get("kfId").toString());
        Storeroom storeroom=storeroomMapper.selectStoreroomByStoreId(kf_id,code);
        //前端如果勾选了全选按钮   需要给 ids 去重
        String ids=String.valueOf(map.get("ids"));//选择上架的盒子或者案卷
        String[] strArray = ids.split(",");
        Set<String> staffsSet = new HashSet<String>(Arrays.asList(strArray));
        String[] result = staffsSet.toArray(new String[staffsSet.size()]);
        String position=String.valueOf(map.get("position"));//点击的位置
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(d);
        //根据ids和门类code查询是哪条数据   把规格查询出来
        String boString="false";
         String type=map.get("type").toString();
        try {
            String sql="";
            for (int i = 0; i < result.length; i++) {//遍历出来是  id+menleicode
                String id = result[i];
                String[] result1 = id.split(";");
                Long id1 = Long.parseLong(result1[0]);
                String subtablename = result1[1];
                //根据subtablename   判断后缀  STORE_MODE整理方式
                ArrayList<Map<String, Object>> singleListBySql = new ArrayList<>();
                String[] subArr = subtablename.split("_");
                if ("F".equals(subArr[subArr.length - 2])) {
                    singleListBySql = upDownShelvesMapper.getCategoryByDa(subtablename, code, "");
                } else if ("V".equals(subArr[subArr.length - 2])) {
                    singleListBySql = upDownShelvesMapper.getCategoryByDa("", code, subtablename);
                }
                String STORE_MODE = singleListBySql.get(0).get("STORE_MODE").toString();
                if (type.equals("1")) {//按卷上架，修改卷表
                    //应该查询出来案卷的规格厚度，这样修改格子的剩余宽度之类的。  算页数（假如1页=1mm）
                    //？？？？？？？为啥是50
                    /*  int zongys = upDownShelvesMapper.getSumYs(id1, code);*/
                    //判断floderId是否存在，存在直接修改，不存在则插入
                    int count = upDownShelvesMapper.getCountByfolderId(id1, code);
                    if (count <= 0) {
                        Box box = new Box();
                        box.setBoxId(SnowflakeIdGenerator.generateId());
                        box.setGridId(gz_id);
                        box.setCreator(SecurityUtils.getUserId());
                        box.setCreateTime(new Date());
                        box.setFolderId(id1);
                        box.setPutawayStatus(2);
                        box.setHePosition(position);
                        box.setSjTime(sdf.format(new Date()));
                        box.setSjType("1");
                        box.setSubTableName(subtablename);
                        boxMapper.insertBox(box);

                    } else {
                        upDownShelvesMapper.updateStateByGrounding(new Date(), position, code, id1, time, SecurityUtils.getUserId(), 0L, gz_id,type);
                    }
                    boString = "true";
                    //根据格子id修改格子表的上架盒数和剩余空间

                    upDownShelvesMapper.updateGridByGrounding(0, gz_id, code);

                    Map<String, Object> map1 = upDownShelvesMapper.getDaMessageById(subtablename, id1);
                    if (map1 == null) {
                        map1 = new HashMap<>();

                    }
                    //自动添加出入库登记记录   根据foLder_id  查询件da_id 循环添加数据
                    UpDownLogs upDownLogs = new UpDownLogs();
                    upDownLogs.setCreator(SecurityUtils.getUserId());
                    upDownLogs.setDaId(id1);
                    upDownLogs.setCreateTime(new Date());
                    upDownLogs.setSubTableName(subtablename);
                    upDownLogs.setSxjgzry(SecurityUtils.getLoginUser().getUser().getNickName());
                    upDownLogs.setSxjrq(new Date());
                    upDownLogs.setType("上架");
                    upDownLogs.setTitle(map1.get("TITLE") == null ? "" : map1.get("TITLE").toString());
                    upDownLogs.setDh(map1.get("DH") == null ? "" : map1.get("DH").toString());
                    upDownLogs.setStoreCode(storeroom.getStoreCode());
                    upDownLogs.setStoreName(storeroom.getStoreName());
                    upDownLogsMapper.insertUpDownLogs(upDownLogs);
                    //卷 SJ_POSITION
                    sql+=" UPDATE "+subtablename+" SET SJ_POSITION='"+position+"' WHERE ID="+id1+"; UPDATE "+code+"_YQFOLDER SET SJ_POSITION='"+position+"' WHERE FOLDER_ID="+id1+"; ";
                    //通过卷获取到所有件去修改 将他的倒数第2位替换或者去Category表里查询表
                    String jianTableName=upDownShelvesMapper.selectTableName(subtablename,new TenantCategory().getTableName());
                    String jianIds=upDownShelvesMapper.selectJianIds(id1,new TenantYqdaFolder().getTableName());
                    if(!StringUtils.isEmpty(jianIds)){
                        sql+=" UPDATE "+jianTableName+" SET SJ_POSITION='"+position+"' WHERE ID in ("+jianIds+"); UPDATE "+code+"_YQDA SET SJ_POSITION='"+position+"' WHERE DA_ID IN ("+jianIds+") ; ";
                    }




                    //插入上下架记录
                } else if (type.equals("0")) {//按盒上架，修改盒表
                     /*Map<String, Object> specMap = upDownShelvesMapper.getSpecByBoxId(id1, code);
                    String dw = specMap.get("SPEC_DW").toString();
                   if (dw.equals("0")) {
                        zhoudu += Integer.parseInt(specMap.get("SPEC_NAME").toString());
                    } else if (dw.equals("1")) {
                        zhoudu += Integer.parseInt(specMap.get("SPEC_NAME").toString()) * 10;
                    }  //修改档案盒的上架时间，上架位置，上架的状态*/
                    int num = upDownShelvesMapper.updateStateByGrounding(new Date(), position, code, 0L, time, SecurityUtils.getUserId(), id1, gz_id,type);
                    if (num > 0) {
                        boString = "true";
                    }

                    upDownShelvesMapper.updateGridByGrounding(0, gz_id, code);

                    ArrayList<Map<String, Object>> hedaidlist = daBoxMapper.getDaIdListByBoxId(id1, code);

                    for (Map map1 : hedaidlist) {
                        String tableName=map1.get("SUB_TABLE_NAME").toString();
                        Map<String, Object> map2 = upDownShelvesMapper.getDaMessageById(tableName, Long.parseLong(map1.get("DA_ID").toString()));
                        if (map2 == null) {
                            map2 = new HashMap<>();

                        }
                        UpDownLogs upDownLogs = new UpDownLogs();
                        upDownLogs.setCreator(SecurityUtils.getUserId());
                        upDownLogs.setDaId(Long.parseLong(map1.get("DA_ID").toString()));
                        upDownLogs.setCreateTime(new Date());
                        upDownLogs.setSubTableName(tableName);
                        upDownLogs.setSxjgzry(SecurityUtils.getLoginUser().getUser().getNickName());
                        upDownLogs.setSxjrq(new Date());
                        upDownLogs.setType("上架");
                        upDownLogs.setTitle(map2.get("TITLE") == null ? "" : map2.get("TITLE").toString());
                        upDownLogs.setDh(map2.get("DH") == null ? "" : map2.get("DH").toString());
                        upDownLogs.setStoreCode(storeroom.getStoreCode());
                        upDownLogs.setStoreName(storeroom.getStoreName());
                        upDownLogsMapper.insertUpDownLogs(upDownLogs);
                        //通过da_id 将表进行
                        String[] tableNameArr = tableName.split("_");

                        if ("F".equals(tableNameArr[tableNameArr.length - 2])) {
                            //件 SJ_POSITION
                          sql+=" UPDATE "+tableName+" SET SJ_POSITION='"+position+"' WHERE ID="+Long.parseLong(map1.get("DA_ID").toString())+"; UPDATE "+code+"_YQDA SET SJ_POSITION='"+position+"' WHERE DA_ID="+Long.parseLong(map1.get("DA_ID").toString())+"; ";


                        } else if ("V".equals(tableNameArr[tableNameArr.length - 2])) {
                            //卷 SJ_POSITION
                            sql+=" UPDATE "+tableName+" SET SJ_POSITION='"+position+"' WHERE ID="+Long.parseLong(map1.get("DA_ID").toString())+"; UPDATE "+code+"_YQFOLDER SET SJ_POSITION='"+position+"' WHERE FOLDER_ID="+Long.parseLong(map1.get("DA_ID").toString())+"; ";
                            //通过卷获取到所有件去修改 将他的倒数第2位替换或者去Category表里查询表
                            String jianTableName=upDownShelvesMapper.selectTableName(tableName,new TenantCategory().getTableName());
                            String jianIds=upDownShelvesMapper.selectJianIds(Long.parseLong(map1.get("DA_ID").toString()),new TenantYqdaFolder().getTableName());
                             if(!StringUtils.isEmpty(jianIds)){
                                 sql+=" UPDATE "+jianTableName+" SET SJ_POSITION='"+position+"' WHERE ID in ("+jianIds+"); UPDATE "+code+"_YQDA SET SJ_POSITION='"+position+"' WHERE DA_ID IN ("+jianIds+") ; ";




                             }


                        }




                    }
                }
            }

        //执行sql
        if(!StringUtils.isEmpty(sql)){
            //如果不为空那么就执行sql
            initializationMapper.createTable(sql);



        }
        }catch (Exception ex){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚
            log.error("上架失败",ex.getMessage());
            throw new ServiceException("上架失败!");

            // boString="false";
            //ex.printStackTrace();
        }
     /*       }*/
/*

        }else {
            return "false";
        }
*/

        return boString;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String relocation(Map map) {
        String code=SecurityUtils.getTenantCode().toUpperCase();
        if(StringUtils.isEmpty(code)){
            ///可能要抛出异常
            throw new ServiceException("TenantCode is null");
        }
        String type=map.get("type").toString();

        Long gz_id= Long.parseLong( map.get("gzId").toString());//原格子id  预留计算空间
        Long gz_id1= Long.parseLong( map.get("newGzId").toString());//现格子id  预留计算空间

        //前端如果勾选了全选按钮   需要给 ids 去重
        String ids=String.valueOf(map.get("ids"));//选择上架的盒子或者案卷
        String[] strArray = ids.split(",");
        Set<String> staffsSet = new HashSet<String>(Arrays.asList(strArray));
        String[] result = staffsSet.toArray(new String[staffsSet.size()]);
        String position1=String.valueOf(map.get("newPosition"));//选择上架的盒子或者案卷

        Date d = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sbf.format(d);
        //根据ids和门类code查询是哪条数据   把规格查询出来
        String boString="false";
          String sql="";
            for (int i = 0; i < result.length; i++) {//遍历出来是  id+menleicode
                String id = result[i];
                String[] result1 = id.split(";");
                Long id1 = Long.parseLong(result1[0]);
                String subtablename = result1[1];
                //根据subtablename   判断后缀  STORE_MODE整理方式
                ArrayList<Map<String, Object>> singleListBySql = new ArrayList<>();
                String[] subArr = subtablename.split("_");
                if ("F".equals(subArr[subArr.length - 2])) {
                    singleListBySql = upDownShelvesMapper.getCategoryByDa(subtablename, code, "");
                } else if ("V".equals(subArr[subArr.length - 2])) {
                    singleListBySql = upDownShelvesMapper.getCategoryByDa("", code, subtablename);
                }
                String STORE_MODE = singleListBySql.get(0).get("STORE_MODE").toString();

                //查询当前剩余空间>总页数   大于的话就能调整，小于的就返回提示空间不足

/*
                Integer residue1 = gridMapper.getResidueSpace(gz_id1, code);
*/

                if (type.equals("1")) {//按卷上架，修改卷表
                    //应该查询出来案卷的规格厚度，这样修改格子的剩余宽度之类的。  算页数（1页=1mm）
               /*     int zongys = upDownShelvesMapper.getSumYs(id1, code);
                    if (residue1 >= zongys) {*/
                        int num = upDownShelvesMapper.updatePosition(gz_id1, id1, position1, code, time, SecurityUtils.getUserId(), new Date(), 0L);
                        //根据现格子id修改格子表的上架盒数和剩余空间
                         upDownShelvesMapper.updateGridByGrounding(0, gz_id1, code);
                         upDownShelvesMapper.updateGridByBox(gz_id,code);


                         //修改位置


                 /*       upDownShelvesMapper.updateGridByGrounding(zongys, gz_id1, code);
                        //根据格子id修改格子表的上架盒数和剩余空间
                        upDownShelvesMapper.updateGridByfolderId(zongys, gz_id, code);*/
                        if (num > 0) {
                            boString = "true";
                      }
                   // Map<String, Object> map1 = upDownShelvesMapper.getDaMessageById(subtablename, id1);
                    //卷 SJ_POSITION
                    sql+=" UPDATE "+subtablename+" SET SJ_POSITION='"+position1+"' WHERE ID="+id1+"; UPDATE "+code+"_YQFOLDER SET SJ_POSITION='"+position1+"' WHERE FOLDER_ID="+id1+"; ";
                    //通过卷获取到所有件去修改 将他的倒数第2位替换或者去Category表里查询表
                    String jianTableName=upDownShelvesMapper.selectTableName(subtablename,new TenantCategory().getTableName());
                    String jianIds=upDownShelvesMapper.selectJianIds(id1,new TenantYqdaFolder().getTableName());
                    if(!StringUtils.isEmpty(jianIds)){
                        sql+=" UPDATE "+jianTableName+" SET SJ_POSITION='"+position1+"' WHERE ID in ("+jianIds+"); UPDATE "+code+"_YQDA SET SJ_POSITION='"+position1+"' WHERE DA_ID IN ("+jianIds+") ; ";
                    }
                    /*  } else {
                        return "101";
                    }*/
                } else if (type.equals("0")) {//按盒上架，修改盒表
                    //应该查询出来盒子的规格厚度，这样修改格子的剩余宽度之类的。 算页数
                /*    Map<String, Object> specMap = upDownShelvesMapper.getSpecByBoxId(id1, code);
                    String dw = specMap.get("SPEC_DW").toString();
                    int guige = 0;
                    if (dw.equals("0")) {
                        guige += Integer.parseInt(specMap.get("SPEC_NAME").toString());
                    } else if (dw.equals("1")) {
                        guige += Integer.parseInt(specMap.get("SPEC_NAME").toString()) * 10;
                    }
                    if (residue1 >= guige) {*/
                        int num = upDownShelvesMapper.updatePosition(gz_id1, 0L, position1, code, time, SecurityUtils.getUserId(), new Date(), id1);
                       upDownShelvesMapper.updateGridByGrounding(0, gz_id1, code);
                       upDownShelvesMapper.updateGridByBox(gz_id,code);
                        if (num > 0) {
                            boString = "true";
                        }
                    ArrayList<Map<String, Object>> hedaidlist = daBoxMapper.getDaIdListByBoxId(id1, code);

                    for (Map map1 : hedaidlist) {
                        String tableName=map1.get("SUB_TABLE_NAME").toString();
                        Map<String, Object> map2 = upDownShelvesMapper.getDaMessageById(tableName, Long.parseLong(map1.get("DA_ID").toString()));
                        if (map2 == null) {
                            map2 = new HashMap<>();

                        }

                        //通过da_id 将表进行
                        String[] tableNameArr = tableName.split("_");

                        if ("F".equals(tableNameArr[tableNameArr.length - 2])) {
                            //件 SJ_POSITION
                            sql+=" UPDATE "+tableName+" SET SJ_POSITION='"+position1+"' WHERE ID="+Long.parseLong(map1.get("DA_ID").toString())+"; UPDATE "+code+"_YQDA SET SJ_POSITION='"+position1+"' WHERE DA_ID="+Long.parseLong(map1.get("DA_ID").toString())+"; ";


                        } else if ("V".equals(tableNameArr[tableNameArr.length - 2])) {
                            //卷 SJ_POSITION
                            sql+=" UPDATE "+tableName+" SET SJ_POSITION='"+position1+"' WHERE ID="+Long.parseLong(map1.get("DA_ID").toString())+"; UPDATE "+code+"_YQFOLDER SET SJ_POSITION='"+position1+"' WHERE FOLDER_ID="+Long.parseLong(map1.get("DA_ID").toString())+"; ";
                            //通过卷获取到所有件去修改 将他的倒数第2位替换或者去Category表里查询表
                            String jianTableName=upDownShelvesMapper.selectTableName(tableName,new TenantCategory().getTableName());
                            String jianIds=upDownShelvesMapper.selectJianIds(Long.parseLong(map1.get("DA_ID").toString()),new TenantYqdaFolder().getTableName());
                            if(!StringUtils.isEmpty(jianIds)){
                                sql+=" UPDATE "+jianTableName+" SET SJ_POSITION='"+position1+"' WHERE ID in ("+jianIds+"); UPDATE "+code+"_YQDA SET SJ_POSITION='"+position1+"' WHERE DA_ID IN ("+jianIds+") ; ";

                            }


                        }




                    }




                   /*     upDownShelvesMapper.updateGridByGrounding(guige, gz_id1, code);
                        upDownShelvesMapper.updateGrid(guige, gz_id1, code);*/

                    /*} else {
                        return "101";
                    }*/
                }
            }
        //执行sql
        if(!StringUtils.isEmpty(sql)){
            //如果不为空那么就执行sql
            initializationMapper.createTable(sql);



        }

        return boString;
    }

    @Override
    public Folder selectFolderById(Long folderId) {
        String code=SecurityUtils.getTenantCode().toUpperCase();
        if(StringUtils.isEmpty(code)){
            throw new ServiceException("TenantCode is null");

        }
        Folder folder=upDownShelvesMapper.getFolderById(folderId,code);
       //List<Map<String,Object>>daList=upDownShelvesMapper.getDaList(folderId,code);
    //    folder.setList(daList);
        return folder;
    }

    @Override
    public Boolean inspectIds(Map map) {
        //验证选中的值里是否有出库的数据
        String code=SecurityUtils.getTenantCode().toUpperCase();
        if(StringUtils.isEmpty(code)){
            throw new ServiceException("TenantCode is null");

        }
        String type=map.get("type").toString();
        String ids=map.get("ids").toString();
        List<Integer> list=new ArrayList<>();
        //按盒上架
        if("0".equals(type)){
           list=upDownShelvesMapper.inspectIdsByDa(ids,code);
        }else if("1".equals(type)){
            list=upDownShelvesMapper.inspectIdsByFolder(ids,code);
        }
       if(list.contains(1)){
           return false;
       }else{
           return true;
       }

        //

    }

    @Override
    public List<Box> printRidgeBox(String ids) {
        String code=SecurityUtils.getTenantCode().toUpperCase();
        if(StringUtils.isEmpty(code)){
            throw new ServiceException("TenantCode is null");
            //抛出异常
        }

        return boxMapper.printRidgeBox(ids,new Box().getTableName());
    }

    @Override
    public String selectPosition(Long gridId) {

        Grid grid=gridMapper.selectGridByGridId(gridId,SecurityUtils.getTenantCode().toUpperCase());
        Shelf shelf=shelfMapper.selectShelfByShelfId(grid.getShelfId(),SecurityUtils.getTenantCode().toUpperCase());
        Storeroom storeroom=storeroomMapper.selectStoreroomByStoreId(shelf.getStoreId(),SecurityUtils.getTenantCode().toUpperCase());
        return storeroom.getStoreName()+" "+shelf.getShelfName()+" "+grid.getGridName();
    }

    @Override
    public List<Yqda> getDalist(Yqda yqda) {
        String type=yqda.getType();
        //盒子
        List<Yqda>list=new ArrayList<>();
        if("0".equals(type)){
            //判断组卷还是组件
            list=upDownShelvesMapper.getyqDaList(SecurityUtils.getTenantCode().toUpperCase(),yqda.getId());

        }else if("1".equals(type)){
            list=upDownShelvesMapper.getFolderDaList(SecurityUtils.getTenantCode().toUpperCase(),yqda.getId());

        }
        return list;
    }
}
